<template>
	<view class="checkin-container">
		<!-- 标题栏 -->
		<view class="header">
			<text class="title">课程纪律打卡</text>
			<text class="subtitle">记录课堂精彩瞬间</text>
		</view>

		<!-- 日期选择 -->
		<view class="date-picker">
			<picker mode="date" :value="currentDate" @change="dateChange">
				<view class="date-input">
					<uni-icons type="calendar" size="20" color="#FF9A9E"></uni-icons>
					<text>{{ currentDate }}</text>
				</view>
			</picker>
		</view>

		<!-- 主题类型选择 -->
		<view class="theme-picker glass-card">
			<view class="theme-header">
				<text>选择打卡主题</text>
				<uni-icons type="plus" size="24" color="#FF9A9E" @click="showAddThemeDialog"></uni-icons>
			</view>

			<scroll-view scroll-x class="theme-scroll">
				<view v-for="(theme, index) in themes" :key="index" class="theme-item"
					:class="{active: selectedTheme === theme}" @click="selectTheme(theme)">
					{{ theme }}
				</view>
			</scroll-view>
		</view>

		<!-- 添加主题弹窗 -->
		<uni-popup ref="themePopup" type="dialog">
			<uni-popup-dialog mode="input" title="添加新主题" placeholder="请输入新主题名称"
				@confirm="addNewTheme"></uni-popup-dialog>
		</uni-popup>

		<!-- 打卡记录列表 -->
		<scroll-view class="checkin-list" scroll-y>
			<view v-if="checkinData.length === 0 && localImages.length === 0" class="empty-tip">
				<!-- <image src="/static/images/empty.png" mode="aspectFit"></image> -->
				<text>暂无打卡数据</text>
			</view>
			<view v-for="(item, index) in checkinData" :key="item.id" class="checkin-card glass-card">
				<view class="card-header">
					<text class="time">{{ formatTime(item.dateTime) }}</text>
					<text class="teacher">{{ item.teacherName }}老师</text>
					<text class="mark-tag" :style="{backgroundColor: getMarkColor(item.mark)}">{{ item.mark }}</text>
				</view>

				<view class="card-content">
					<image :src="globalVariable + '/getLessonCheckImage/' + item.imgPath" mode="aspectFill"
						class="checkin-image" @click="previewImage(index)"></image>
				</view>
			</view>

			<!-- 本地预览区域 -->
			<view v-if="localImages.length > 0" class="preview-area glass-card">
			  <view class="preview-header">
			    <text>待提交照片 (已压缩)</text>
			    <text class="preview-count">{{ localImages.length }}张</text>
			  </view>
				<scroll-view scroll-x class="preview-scroll">
					<view v-for="(img, index) in localImages" :key="index" class="preview-item">
						<image :src="img" mode="aspectFill" class="preview-image"></image>
						<view v-if="isUploading" class="progress-bar">
							<view class="progress-fill" :style="{width: (uploadProgress[index] || 0) + '%'}"></view>
						</view>
						<uni-icons type="close" size="24" color="#ff5a5f" class="delete-icon"
							@click="removeLocalImage(index)"></uni-icons>
					</view>
				</scroll-view>
			</view>

			<!-- 上传区域 - 仅今天显示 -->
			<view v-if="isToday" class="upload-area glass-card">
				<view class="upload-header">
					<text class="upload-title">今日待打卡课程</text>
					<text class="upload-subtitle">已完成 {{ completedCount }}/5</text>
				</view>

				<view class="upload-content">
					<view class="upload-card" @click="chooseImage">
						<view class="upload-btn">
							<uni-icons type="plusempty" size="48" color="#FF9A9E"></uni-icons>
							<text class="upload-text">添加打卡照片</text>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部操作栏 - 仅今天且有本地图片时显示 -->
		<view class="action-bar glass-card" v-if="isToday && localImages.length > 0">
			<button class="action-btn" @click="!isUploading && submitImages()" :disabled="isUploading">
				<uni-icons type="upload" size="20" color="#fff"></uni-icons>
				<text>{{ isUploading ? '正在上传...' : '上传图片' }}</text>
			</button>
		</view>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';
	export default {
		data() {
			return {
				currentDate: this.formatDate(new Date()),
				checkinData: [],
				teacherId: null,
				teacherName: '',
				localImages: [],
				themes: ['纪律良好', '课堂活跃', '自习安静', '学习刻苦'],
				selectedTheme: '纪律良好',
				globalVariable,
				uploadProgress: {},
				isUploading: false,
				uploadStatus: {
					isUploading: false,
					totalProgress: 0,
					uploadedCount: 0,
					totalCount: 0
				}
			}
		},
		computed: {
			// 是否是今天
			isToday() {
				return this.currentDate === this.formatDate(new Date());
			},
			// 已完成数量（包括已上传和本地缓存）
			completedCount() {
				const myCheckins = this.checkinData;
				return myCheckins.length + this.localImages.length;
			},
			// 还可以上传的数量
			remainingCount() {
				return Math.max(0, 10 - this.completedCount);
			}
		},
		onLoad(option) {
			this.grade = option.grade
			this.loadTeacherInfo();
			this.fetchCheckinData();

		},
		methods: {

			// 新增的图片压缩方法
			async compressImage(filePath, quality = 0.7, maxWidth = 1024) {
				return new Promise((resolve) => {
					uni.getImageInfo({
						src: filePath,
						success: (imageInfo) => {
							const canvas = document.createElement('canvas');
							const ctx = canvas.getContext('2d');

							// 计算压缩后的尺寸
							let width = imageInfo.width;
							let height = imageInfo.height;
							if (width > maxWidth) {
								height = (maxWidth / width) * height;
								width = maxWidth;
							}

							canvas.width = width;
							canvas.height = height;

							const img = new Image();
							img.onload = () => {
								ctx.drawImage(img, 0, 0, width, height);
								canvas.toBlob((blob) => {
									// 将Blob转换为临时文件路径
									const reader = new FileReader();
									reader.onload = () => {
										resolve({
											path: reader.result,
											width,
											height,
											size: blob.size
										});
									};
									reader.readAsDataURL(blob);
								}, 'image/jpeg', quality);
							};
							img.src = filePath;
						},
						fail: () => {
							// 压缩失败则返回原图
							resolve({
								path: filePath
							});
						}
					});
				});
			},
			loadTeacherInfo() {
				uni.getStorage({
					key: 'teacher',
					success: (res) => {
						this.teacherId = res.data.teacherId;
						this.teacherName = res.data.name;
					}
				});
			},
			fetchCheckinData() {
				uni.showLoading({
					title: '加载中...'
				});

				uni.request({
					url: `${globalVariable}/getLessonCheckByGrade`,
					data: {
						grade: this.grade,
						dateTime: this.currentDate
					},
					success: (res) => {
						uni.hideLoading();
						if (res.data.status === 1) {
							this.checkinData = res.data.data;
							this.checkinData.sort((a, b) => new Date(a.dateTime) - new Date(b.dateTime));
						} else {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						});
					}
				});
			},
			dateChange(e) {
				this.currentDate = e.detail.value;
				this.localImages = []; // 切换日期清空本地缓存
				this.fetchCheckinData();
			},
			formatDate(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			formatTime(datetime) {
				if (!datetime) return '';
				const timePart = datetime.includes('T') ?
					datetime.split('T')[1].substring(0, 5) :
					datetime.split(' ')[1].substring(0, 5);
				return timePart;
			},
			getMarkColor(mark) {
				if (mark.includes('优秀')) return 'rgba(144, 238, 144, 0.7)';
				if (mark.includes('良好')) return 'rgba(173, 216, 230, 0.7)';
				if (mark.includes('需要')) return 'rgba(255, 182, 193, 0.7)';
				return 'rgba(211, 211, 211, 0.7)';
			},
			previewImage(index) {
				const urls = this.checkinData.map(item =>
					globalVariable + '/getLessonCheckImage/' + item.imgPath
				);
				uni.previewImage({
					current: urls[index],
					urls: urls
				});
			},
			chooseImage() {
			  if (this.remainingCount <= 0) {
			    uni.showToast({
			      title: '今日打卡已完成',
			      icon: 'none'
			    });
			    return;
			  }
			
			  uni.chooseImage({
			    count: this.remainingCount,
			    sizeType: ['original'], // 改为获取原图，我们自己压缩
			    sourceType: ['album', 'camera'],
			    success: async (res) => {
			      // 显示压缩进度
			      uni.showLoading({
			        title: '正在压缩图片...',
			        mask: true
			      });
			      
			      // 压缩所有选择的图片
			      const compressedImages = [];
			      for (const tempFilePath of res.tempFilePaths) {
			        const compressed = await this.compressImage(tempFilePath);
			        compressedImages.push(compressed.path);
			      }
			      
			      uni.hideLoading();
			      this.localImages = [...this.localImages, ...compressedImages];
			    }
			  });
			},
			removeLocalImage(index) {
				this.localImages.splice(index, 1);
			},
			selectTheme(theme) {
				this.selectedTheme = theme;
			},
			showAddThemeDialog() {
				this.$refs.themePopup.open();
			},
			addNewTheme(value) {
				if (value && !this.themes.includes(value)) {
					this.themes.push(value);
					this.selectedTheme = value;
				}
				this.$refs.themePopup.close();
			},
			async submitImages() {
				if (this.localImages.length === 0) {
					uni.showToast({
						title: '请先选择照片',
						icon: 'none'
					});
					return;
				}

				this.isUploading = true;
				this.uploadProgress = {}; // 重置进度

				try {
					// 使用Promise.all并行上传
					await Promise.all(this.localImages.map((imgPath, index) => {
						return this.uploadSingleImage(imgPath, index);
					}));

					uni.showToast({
						title: '上传完成',
						icon: 'success'
					});
					this.localImages = [];
					this.fetchCheckinData();
				} catch (error) {
					uni.showToast({
						title: '上传失败: ' + error,
						icon: 'none'
					});
				} finally {
					this.isUploading = false;
				}
			},
			uploadSingleImage(imgPath, index) {
			  return new Promise(async (resolve, reject) => {
			    try {
			      // 先压缩再上传
			      const compressed = await this.compressImage(imgPath);
			      
			      const uploadTask = uni.uploadFile({
			        url: `${globalVariable}/uploadLessonCheck`,
			        filePath: compressed.path,
			        name: 'file',
			        formData: {
			          teacherId: this.teacherId,
			          teacherName: this.teacherName,
			          grade: this.grade,
			          dateTime: new Date().toISOString(),
			          mark: this.selectedTheme
			        },
			        success: (res) => {
			          const data = JSON.parse(res.data);
			          if (data.status !== 1) {
			            reject(data.message);
			          } else {
			            resolve();
			          }
			        },
			        fail: (err) => {
			          reject(err);
			        }
			      });
			
			      uploadTask.onProgressUpdate((res) => {
			        this.$set(this.uploadProgress, index, res.progress);
			      });
			    } catch (error) {
			      reject(error);
			    }
			  });
			}
		}
	}
</script>

<style lang="scss" scoped>
	.preview-item {
		position: relative;
		/* 其他样式不变 */
	}

	.progress-bar {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 6rpx;
		background: rgba(255, 255, 255, 0.3);
		border-radius: 0 0 12rpx 12rpx;
		overflow: hidden;
	}

	.progress-fill {
		height: 100%;
		background: #424bff;
		transition: width 0.3s;
	}

	.empty-tip {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
		text-align: center;
	}

	/* 样式部分保持不变，与之前相同 */
	.checkin-container {
		padding: 30rpx;
		min-height: 100vh;
		background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
		background-image:
			radial-gradient(circle at 10% 20%, rgba(255, 15, 51, 0.1) 0%, transparent 20%),
			radial-gradient(circle at 90% 80%, rgba(8, 255, 111, 0.1) 0%, transparent 20%);

		.header {
			margin-bottom: 40rpx;
			text-align: center;

			.title {
				display: block;
				font-size: 42rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 10rpx;
			}

			.subtitle {
				display: block;
				font-size: 26rpx;
				color: #888;
			}
		}

		.date-picker {
			margin-bottom: 30rpx;

			.date-input {
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 20rpx;
				background: rgba(255, 255, 255, 0.6);
				border-radius: 50rpx;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

				text {
					margin-left: 10rpx;
					font-size: 28rpx;
					color: #666;
				}
			}
		}

		.theme-picker {
			margin-bottom: 30rpx;
			padding: 20rpx;
			border-radius: 24rpx;

			.theme-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;
				font-size: 28rpx;
				color: #333;
			}

			.theme-scroll {
				white-space: nowrap;

				.theme-item {
					display: inline-flex;
					padding: 12rpx 24rpx;
					margin-right: 20rpx;
					background: rgba(255, 255, 255, 0.4);
					border-radius: 40rpx;
					font-size: 26rpx;
					color: #666;

					&.active {
						background: #FF9A9E;
						color: #fff;
						font-weight: bold;
					}
				}
			}
		}

		.checkin-list {
			height: calc(100vh - 380rpx);
			padding-bottom: 120rpx;

			.checkin-card {
				margin-bottom: 30rpx;
				padding: 30rpx;
				border-radius: 24rpx;

				.card-header {
					display: flex;
					align-items: center;
					margin-bottom: 20rpx;

					.time {
						font-size: 28rpx;
						font-weight: bold;
						color: #333;
						margin-right: 20rpx;
					}

					.teacher {
						font-size: 26rpx;
						color: #666;
						margin-right: 20rpx;
					}

					.mark-tag {
						padding: 6rpx 16rpx;
						border-radius: 30rpx;
						font-size: 24rpx;
						color: #fff;
					}
				}

				.card-content {
					.checkin-image {
						width: 100%;
						height: 400rpx;
						border-radius: 16rpx;
					}
				}
			}

			.preview-area {
				margin-bottom: 30rpx;
				padding: 30rpx;
				border-radius: 24rpx;

				.preview-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 20rpx;
					font-size: 28rpx;
					color: #333;

					.preview-count {
						font-size: 26rpx;
						color: #FF9A9E;
					}
				}

				.preview-scroll {
					white-space: nowrap;

					.preview-item {
						position: relative;
						display: inline-block;
						width: 200rpx;
						height: 200rpx;
						margin-right: 20rpx;

						.preview-image {
							width: 100%;
							height: 100%;
							border-radius: 12rpx;
						}

						.delete-icon {
							position: absolute;
							top: -10rpx;
							right: -10rpx;
							background: #fff;
							border-radius: 50%;
							padding: 4rpx;
							box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
						}
					}
				}
			}

			.upload-area {
				padding: 30rpx;
				border-radius: 24rpx;

				.upload-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 30rpx;

					.upload-title {
						font-size: 30rpx;
						font-weight: bold;
						color: #333;
					}

					.upload-subtitle {
						font-size: 26rpx;
						color: #FF9A9E;
					}
				}

				.upload-content {
					.upload-card {
						.upload-btn {
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: center;
							height: 300rpx;
							background: rgba(255, 255, 255, 0.4);
							border-radius: 16rpx;
							border: 2rpx dashed #FF9A9E;

							.upload-text {
								margin-top: 20rpx;
								font-size: 26rpx;
								color: #FF9A9E;
							}
						}
					}
				}
			}
		}

		.action-bar {
			position: fixed;
			bottom: 30rpx;
			left: 30rpx;
			right: 30rpx;
			padding: 20rpx;
			border-radius: 50rpx;
			display: flex;
			justify-content: center;

			.action-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 100%;
				height: 80rpx;
				background: linear-gradient(135deg, #FF9A9E 0%, #FBC2EB 100%);
				color: #fff;
				font-size: 28rpx;
				border-radius: 40rpx;
				box-shadow: 0 4rpx 12rpx rgba(255, 154, 158, 0.3);

				text {
					margin-left: 10rpx;
				}
			}
		}
	}

	/* 毛玻璃效果 */
	.glass-card {
		background: rgba(255, 255, 255, 0.6);
		backdrop-filter: blur(20px);
		-webkit-backdrop-filter: blur(20px);
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
		border: 1px solid rgba(255, 255, 255, 0.4);
	}
</style>